import { syncRoutes } from './router'
import router from './router'
import store from './store'
import { getToken } from './utils/auth'

const list = ['/login', '/404']

// 得到一级路由菜单的权限点
function getFirstRoute(perms) {
  const arr = perms.map(item => {
    // item是一个字符串
    return item.split(':')[0]
  })
  return arr
}
// 得到二级路由菜单的权限点

function getSecondRoute(perms) {
  const arr = perms.map(item => {
    // item是一个字符串
    return item.split(':')[0] + ':' + item.split(':')[1]
  })
  return arr
}
// 根据权限过滤路由
function getSyncRouter(frist, second) {
  if (frist.includes('*')) {
    return syncRoutes
  }
  const fristRouter = syncRoutes.filter(item => {
    return frist.includes(item.permission)
  })
  const res = fristRouter.map(fristItem => {
    const children = fristItem.children.filter(secondItem => {
      return second.includes(secondItem.permission)
    })
    fristItem.children = children
    return fristItem
  })
  return res
}
// 路由前置守卫
// to：去哪儿
// from：从哪儿来
// next：是否放行的函数
router.beforeEach(async(to, from, next) => {
  const token = getToken()
  if (token) {
    next()
    // 确保已经拿到了token,获取用户权限点
    if (!store.state.user.profile.id) {
      // store.dispatch('user/getProfile')
      const perms = await store.dispatch('user/getProfile')
      // 一级路由菜单的权限
      const frist = [...new Set(getFirstRoute(perms))]
      // console.log('一级菜单', frist)
      // 二级路由菜单的权限
      const second = [...new Set(getSecondRoute(perms))]
      // console.log('二级菜单', second)
      const res = getSyncRouter(frist, second)
      console.log(res)

      res.forEach(item => {
        router.addRoute(item)
      })
      store.commit('menu/setRouteList', res)
    }
  } else {
    if (list.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
